// vars/sshNodeJSDeploy.groovy

def call(body) {
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config

    body()

    properties([parameters([choice(choices: ['develop', 'publish'], description: '构建环境', name: 'PROFILE')])])

    assert(config.APP_NAME)
    assert(config.HOSTS)
    assert(config.REMOTE_PATH)

    /* 构建环境 */
    def PFILE = params.PROFILE    
    /* 各环境部署服务器,一个环境部署多个主机使用逗号隔开 */      
    def SVRS_ENV = config.HOSTS
    def SVRS = SVRS_ENV["${PFILE}"]   
    def SERVERS = SVRS.split(',')   
    def APP_NAME = config.APP_NAME  
    def REMOTE_APP_PATH = config.REMOTE_PATH
    
    stage('Checkout') {
      checkout scm    
    }
    
    stage('Build') {
        sh """
            echo 'npm config'
            npm config set registry http://registry.npm.taobao.org/
            npm config get registry
            npm config get prefix
            npm config get cache
            
            rm -rf ${APP_NAME}
            npm install --save node-sass --registry=https://registry.npm.taobao.org --disturl=https://npm.taobao.org/dist --sass-binary-site=http://npm.taobao.org/mirrors/node-sass
            npm install
            echo 'npm install success'
            npm run build:${PFILE}
            echo 'npm run build success'

            mv dist ${APP_NAME}
        """
    }
   
    stage('Deploy') {
        for(int i=0;i<SERVERS.length;i++){
            def svr = SERVERS[i];
            println svr
            def item = svr.split('@')
            def user = item[0]
            def host = item[1]

            println REMOTE_APP_PATH
            /* 确认远程主机目录已创建 */
            sh """ssh -Tq ${svr} <<EOF
                  echo ${REMOTE_APP_PATH} 
                  mkdir -p ${REMOTE_APP_PATH}
                  rm -rf ${REMOTE_APP_PATH}/${APP_NAME}/*
EOF"""
            
            /* 将应用部署到远程主机 */                        
            def targetDir = svr + ":" + REMOTE_APP_PATH + "/" + APP_NAME + "/"
            sh """scp -r ${APP_NAME}/* ${targetDir}
               """
        }                 
    }
}